package com.atguigu.bookcity.controller;


import com.atguigu.bookcity.entity.Role;
import com.atguigu.bookcity.exception.BookCityException;
import com.atguigu.bookcity.mapper.UserRoleMapper;
import com.atguigu.bookcity.service.RoleService;
import com.atguigu.bookcity.vo.CommonResult;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zsc
 * @since 2021-05-29
 */
@CrossOrigin
@RestController
@Api(tags = {"角色管理"})
@RequestMapping("/bookcity/role")
public class RoleController {

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RoleService roleService;

    @ApiOperation(
            value = "获取本系统所有角色",
            notes = "本系统所有角色的List",
            produces = "application/json")
    @GetMapping("/getAllRoles")
    @RequiresRoles(value = {"admin","manager"},logical = Logical.OR)
    public CommonResult getAllRoles() {
        List<String> roles = userRoleMapper.getRoles();
        return CommonResult.ok().data("roles", roles);
    }

    @ApiOperation(
            value = "为本系统新添角色",
            notes = "admin权限使用该接口",
            produces = "application/json")
    @RequiresRoles("admin")
    @PostMapping("/addRole")
    public CommonResult addRole(@RequestParam String roleName) {
        List<String> roles = userRoleMapper.getRoles();
        if (roles.contains(roleName))
            throw new BookCityException(201,"角色已存在");
        Role role = new Role();
        role.setName(roleName);
        if (!roleService.save(role))
            return CommonResult.error();
        return CommonResult.ok();
    }

    @ApiOperation(
            value = "修改角色名称",
            notes = "admin权限使用该接口",
            produces = "application/json")
    @RequiresRoles("admin")
    @PostMapping("/updateRoleByName")
    public CommonResult updateRole(@RequestParam String oldName,
                                   @RequestParam String newName){
        UpdateWrapper<Role> wrapper = new UpdateWrapper<>();
        wrapper.eq("name",oldName)
                .set("name",newName);
        roleService.update(wrapper);
        return CommonResult.ok();
    }


}

